package com.chujian.framework.mybatis.tenant;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.chujian.framework.auth.AccessorHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

/**
 * 多租户处理器
 */
public class ChujianTenantLineHandler implements TenantLineHandler {

    private TenantProperties tenantProperties;

    public ChujianTenantLineHandler(TenantProperties tenantProperties) {
        this.tenantProperties = tenantProperties;
    }

    @Override
    public Expression getTenantId() {
        Long acId = AccessorHolder.getAcId();
        return new LongValue(acId);
    }

    @Override
    public String getTenantIdColumn() {
        return "ac_id";
    }

    /**
     * 配置不需要根据租户隔离的表
     *
     * @param tableName 表名
     * @return true:表示忽略多租户，false:需要解析并拼接多租户条件
     */
    @Override
    public boolean ignoreTable(String tableName) {
        // 逻辑忽略
        boolean ignore = LogicIgnoreAcTableHolder.getIgnoreTables()
                .stream()
                .anyMatch((e) -> e.equalsIgnoreCase(tableName));
        if (ignore) {
            return true;
        }
        // 配置忽略
        return tenantProperties.getIgnoreTables()
                .stream()
                .anyMatch((e) -> e.equalsIgnoreCase(tableName));
    }
}
